package com.crm.controller;

import com.crm.domain.DataGridView;
import com.crm.pojo.Permission;
import com.crm.service.PermissionService;
import com.crm.service.RoleService;
import com.crm.util.ResultDto;
import com.crm.vo.RoleVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.List;

@RestController
public class RoleController {
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @GetMapping("/roles.do")
    public DataGridView getUserList(RoleVo roleVo){
        return roleService.findAllRoles(roleVo);
    }
    @GetMapping("/role/perMenus.do")
    public List<Permission> perMenus(){
        return this.permissionService.selectAllMenus();
    }
    @GetMapping(value = "/role/getCheckedMenu.do")
    public Integer[] getCheckedMenu(Integer rid){
        List<Permission> permissionList=permissionService.selectMenuIdsByRid(rid);
        Integer[] permissionIds=new Integer[permissionList.size()];
        for(int i=0;i<permissionList.size();i++){
            permissionIds[i]=permissionList.get(i).getId();
        }
        return permissionIds;
    }
    @PostMapping(value = "/role/doAssignPermission.do")
    public ResultDto doAssignPermission(Integer rid, String menuIdsStr){
        ResultDto dto=new ResultDto();
        if(menuIdsStr!=null&&menuIdsStr.length()>0){
            String[] menuIdArray=menuIdsStr.split(",");
            Integer[] menuIds=new Integer[menuIdArray.length];
            for (int i=0;i<menuIdArray.length;i++) {
                menuIds[i]=Integer.parseInt(menuIdArray[i]);
            }
            boolean flag=this.roleService.doAssignMenuByRoleId(rid,menuIds);
            if(flag){
                dto.setCode(200);
            }else{
                dto.setCode(-1);
            }
        }
        return dto;
    }
}
